﻿using log4net;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Models.Common;
using PlaceOrder_Shared.Models.Daily;
using PlaceOrder_Shared.Models.Enum;
using PlaceOrder_Shared.Models.Trade;
using PlaceOrder_Shared.ModelsToLily;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
using DevExpress.Mvvm.Native;
using System.Net.Http;
using Microsoft.EntityFrameworkCore.ValueGeneration.Internal;
using Microsoft.Extensions.Logging.Abstractions;
namespace PlaceOrder_Core.Services.Instances
{
    public class UserHelper : IUserHelper
    {
        public static string UserName { get; set; }
        public static int UserID { get; set; }
        public static string Token = "";
        public static string NickName = "";
        public static UserTypeEnum UserType;
        public static string LoginIP = "";
        public string Password { get; set; }
        public static UserTradeLimit TradeLimit;
        private string CookieFile = "cookie.dat";
        private static int TimeOut = 3000;
        private string loginBody = "{\"username\":\"_USERNAME_\",\"password\":\"_PASSWORD_\",\"hwinfo\":\"_HWINFO_\"}";
        public SimTradeUserStatusEnmu simTradeUserStatusEnmu;
        public enum SimTradeUserStatusEnmu
        {
            Normal,
            OnlyBalance,
            ForbidToday,
            ForbidForever
        }
        #region 接口方法
        public bool AddUser(UserInfo ui, out string msg)
        {
            msg = "1";
            return true;
        }

        /// <summary>
        /// 新增询价单接口
        /// </summary>
        /// <param name="trade"></param>
        /// <param name="UserToken"></param>
        /// <param name="UserTradeID"></param>
        /// <param name="msg"></param>
        /// <param name="ActualVolume"></param>
        /// <param name="ChangePriceTradeIDs"></param>
        /// <param name="brokerId"></param>
        /// <param name="orderMessage"></param>
        /// <returns></returns>
        public int AddUserTrade(UserTrade trade, string UserToken, out int UserTradeID, out string msg, out int ActualVolume, ref string ChangePriceTradeIDs, out int brokerId, out string orderMessage)
        {
            msg = "";
            UserTradeID = 0;
            ActualVolume = 0;
            orderMessage = string.Empty;
            try
            {

                AppLog.WriteInfo("客户端原生trade" + "AddUserTrade" + trade.ToString());
                LilyTradeModel model = new LilyTradeModel(trade);

                string tmp = JsonConvert.SerializeObject(model);

                AppLog.WriteInfo("客户端原生tmp" + "AddUserTrade" + tmp.ToString());

                using (var client = new HttpClient())
                {
                    HttpContent content = new StringContent(tmp);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");

                    client.DefaultRequestHeaders.Add("Authorization", UserToken);

                    HttpResponseMessage res = client.PostAsync(string.Format($"{DataHelper.BaseConfig.HttpUrl}/usertrade/add"), content).Result;
                    tmp = res.Content.ReadAsStringAsync().Result;
                    if (res.StatusCode == HttpStatusCode.OK)
                    {
                        tmp = res.Content.ReadAsStringAsync().Result;
                    }
                }
                JObject o = JObject.Parse(tmp);
                orderMessage = string.Empty;

                AppLog.WriteInfo("UserHelper" + "Lily返回下单" + o.ToString());
                //AppLog.WriteError("UserHelper" + "AddUserTrade(UserTrade trade, string UserToken, out int UserTradeID..." + msg);

                if (o["code"] == null)
                {
                    msg = "Code not found";
                    brokerId = 0;
                    AppLog.WriteError("UserHelper" + "AddUserTrade(UserTrade trade, string UserToken, out int UserTradeID..." + msg);
                    return 1;
                }
                switch (o["code"].ToString())
                {
                    case "00000":
                        UserTradeID = int.Parse(o["value"]["userTradeId"].ToString());
                        ActualVolume = int.Parse(o["value"]["volume"].ToString());
                        msg = o["value"]["message"].ToString();
                        orderMessage = o["value"].ToString();
                        brokerId = int.Parse(o["value"]["brokerId"].ToString());
                        return 0;
                    case "00002":
                        UserTradeID = int.Parse(o["value"]["userTradeId"].ToString());
                        ActualVolume = int.Parse(o["value"]["volume"].ToString());
                        msg = o["message"].ToString();
                        brokerId = 0;
                        return 2;
                    case "00001":
                        msg = o["message"].ToString();
                        brokerId = 0;
                        return 1;


                    ///重定向，功能未完成，06/21
                    case "00003":
                        msg = o["message"].ToString();
                        ChangePriceTradeIDs = o["value"]["gaijiaTradeIds"].ToString();
                        brokerId = 0;
                        return 3;
                    default:
                        msg = o["message"].ToString();
                        brokerId = 0;
                        return 1;
                }
                brokerId = 0;
                orderMessage = string.Empty;
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "UserHelper" + "AddUserTrade(UserTrade trade, string UserToken, out int UserTradeID..." + ex.StackTrace);
                msg = ex.Message;
                brokerId = 0;
                orderMessage = string.Empty;
                return 1;
            }
        }








        public bool LoginCandleMaintain(out string msg)
        {
            msg = "1";
            return true;
        }

        public bool ModifyUserTrade(UserTrade trade, string UserToken, out string msg, out string returnMsg)
        {
            HttpWebRequest request;

            StreamReader myStreamReader;

            request = (HttpWebRequest)WebRequest.Create($"{DataHelper.BaseConfig.HttpUrl}/usertrade/changerequest");
            request.Method = "Post";
            request.Accept = "application/json";
            request.UserAgent = "BondHelper";
            request.ContentType = "application/json; charset=utf-8";
            request.Headers.Add("Authorization", UserToken);
            request.ProtocolVersion = HttpVersion.Version11;
            request.Timeout = TimeOut;
            request.ServicePoint.Expect100Continue = false;
            LilyTradeModel model = new LilyTradeModel(trade);

            string tmp = JsonConvert.SerializeObject(model);
            AppLog.WriteInfo("客户端原生trade" + "ModifyUserTrade" + tmp.ToString());
            var postData = Encoding.UTF8.GetBytes(tmp);
            request.ContentLength = postData.Length;
            request.KeepAlive = false;
            var postStream = request.GetRequestStream();
            postStream.Write(postData, 0, postData.Length);
            postStream.Close();
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                try
                {
                    myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    string loginModel = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myStreamReader.Dispose();
                    JObject o = JObject.Parse(loginModel);
                    AppLog.WriteInfo("UserHelper" + "Lily返回改价" + o.ToString());
                    msg = o["message"].ToString();


                    if (o["code"].ToString() == "00000")
                    {
                        returnMsg = o["message"].ToString();
                        msg = o["value"]["message"].ToString();
                        return true;
                    }
                    else
                    {
                        returnMsg = o["message"].ToString();
                        msg = o["message"].ToString();
                        return false;
                    }
                    returnMsg = null;
                }

                catch (Exception ex)
                {
                    msg = ex.Message;
                    returnMsg = ex.Message;
                    AppLog.WriteError("ModifyUserTrade异常" + ex.Message + ex.StackTrace);
                    return false;
                }
                finally
                {
                    response.Close();
                    response.Dispose();
                }
            }
        }

        public bool UpdateUser(UserInfo ui, out string msg)
        {
            msg = "1";
            return true;
        }

        public async Task<(string, bool)> Login(UserInfo userInfo, int i = 0)
        {
            string msg = "";
            bool isSuccess = false;
            try
            {
                string userName = userInfo.userName;
                string passWord = userInfo.password;
                UserName = userName;
                string tmp = loginBody.Replace("_USERNAME_", userName);
                tmp = tmp.Replace("_PASSWORD_", passWord);
                MD5 md5 = MD5.Create();
                string hwMD5 = BitConverter.ToString(md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(this.GetMacAddress())));
                hwMD5 = hwMD5.Replace("-", "");
                //hwMD5 = BitConverter.ToString(md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(hwMD5)));
                tmp = tmp.Replace("_HWINFO_", hwMD5.ToLower());
                using (var client = new HttpClient())
                {
                    HttpContent content = new StringContent(tmp);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    string httpUrl;
                    if (i == 1)
                    {
                        httpUrl = DataHelper.BaseConfig.LilyHttpUrl;
                    }
                    else
                    {
                        httpUrl = DataHelper.BaseConfig.HttpUrl;
                    }
                    HttpResponseMessage res = await client.PostAsync(string.Format($"{httpUrl}/login"), content);

                    if (res.StatusCode == HttpStatusCode.OK)
                    {
                        tmp = await res.Content.ReadAsStringAsync();
                    }
                    else
                    {
                        msg = "请求失败: " + res.ReasonPhrase;
                        return (msg, isSuccess);
                    }
                }

                JObject o = JObject.Parse(tmp);
                if (o["code"].ToString() == "200")
                {
                    Token = o["token"].ToString();
                    AppLog.WriteInfo("记录token" + Token);
                    //UserID = _daily.GetUserID(UserName, out NickName);
                    GetLocalIP();
                    AppLog.WriteInfo($"用户{UserHelper.NickName}登录成功！");
                    isSuccess = true;
                }
                else
                {
                    msg = o["message"].ToString();
                    AppLog.WriteInfo($"用户{UserHelper.NickName}登录异常！，{msg}");
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "UserHelper" + "Login" + ex.StackTrace);
                msg = ex.Message;
            }

            return (msg, isSuccess);
        }
        #endregion

        #region 构造函数
        private readonly IDatabase _database;
        private readonly IData _data;
        private readonly ILog _log;
        public UserHelper(IDatabase database, IData data, ILog log)
        {
            _database = database;
            _data = data;
            _log = log;

        }
        #endregion

        #region 辅助方法
        public void GetLocalIP()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    LoginIP = ip.ToString();
                }
            }
        }
        #endregion

        #region 静态方法
        public static List<UserInfo> GetAllUser(out string msg, int i = 0)
        {
            if (Token == "")
            {
                msg = "请先登录";
                return new List<UserInfo>();
            }
            HttpWebRequest request;

            msg = "";
            StreamReader myStreamReader;
            string httpUrl;
            if (i == 0)
            {
                httpUrl = DataHelper.BaseConfig.HttpUrl;
            }
            else
            {
                httpUrl = DataHelper.BaseConfig.LilyHttpUrl;
            }
            request = (HttpWebRequest)WebRequest.Create($"{httpUrl}/system/user/list");
            request.Method = "Get";
            request.Accept = "application/json";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36";
            request.ContentType = "application/json; charset=utf-8";
            request.Headers.Add("Authorization", Token);
            request.KeepAlive = true;
            request.Timeout = TimeOut;
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                try
                {

                    myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    string result = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myStreamReader.Dispose();

                    var jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
                    UserInfoQuery uiq = JsonConvert.DeserializeObject<UserInfoQuery>(result, jSetting);
                    return uiq.rows;
                }
                catch (WebException ex)
                {
                    var response_ex = (HttpWebResponse)ex.Response;
                    myStreamReader = new StreamReader(response_ex.GetResponseStream(), Encoding.UTF8);
                    string result = myStreamReader.ReadToEnd();
                    JObject o = JObject.Parse(result);
                    msg = o["message"].ToString();
                    return new List<UserInfo>();
                }
                finally
                {
                    response.Close();
                    response.Dispose();
                }
            }
        }

        /// <summary>
        /// 用户是否有管理员权限
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public bool CheckAdminRole(int userID)
        {
            try
            {
                using (var db = _database.GetReaderContext())
                {
                    if (!db.IsDbConnectionOpen())
                    {
                        return false;
                    }
                    var user = db.SysUserRoles.Where(o => o.UserId == userID).FirstOrDefault();
                    if (user.RoleId != 3)
                    {
                        return true;
                    }

                }

            }
            catch (Exception ex)
            {
                AppLog.WriteError("CheckAdminRole报错" + ex.Message);
                return false;
            }
            return false;
        }


        #endregion

        #region 客户端相关接口实现

        #endregion

        #region 测试对接刘
        //public void static List<LilyTrade> SelectAllUserTrade()
        //{


        //    try
        //    {
        //        string tmp = string.Empty;

        //        // 构建 URL，包含 userName 参数

        //        //var testName = "Mandarava";
        //        string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/usertrade/listByCurrentUser?userName={UserHelper.NickName}";
        //        using (var client = new HttpClient())
        //        {
        //            // 设置请求头
        //            client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
        //            client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

        //            // 发送 GET 请求
        //            //HttpResponseMessage res = client.GetAsync(apiUrl).Result;
        //            HttpResponseMessage res = await client.GetAsync(apiUrl);  // 使用 await 异步等待
        //            // 读取响应内容
        //            //tmp = res.Content.ReadAsStringAsync().Result;

        //            // 检查响应状态码
        //            if (res.IsSuccessStatusCode)
        //            {
        //                 tmp = await res.Content.ReadAsStringAsync();  // 使用 await 异步等待
        //                // 解析 JSON 响应
        //                //var WeiYueLilyTrades = JsonConvert.DeserializeObject<List<LilyOccupyBrokerInfo>(tmp);

        //                return null;
                     
        //            }
        //            else
        //            {
        //                // 处理请求失败或者错误状态码的情况
        //                Console.WriteLine($"请求失败：{res.StatusCode} - {res.ReasonPhrase}");
        //                return null;

        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        // Handle exceptions as necessary
        //        Console.WriteLine($"Error: {ex.Message}");
        //    }
        //    finally
        //    {
        //        //return null;
        //    }
        //    return null;
        //}



        public int PingCangUserTrade(UserTrade trade, string UserToken, out string msg,out int returnBrokerId)
        {
            msg = "";
            try
            {
                AppLog.WriteInfo($"平仓下单{trade.ToString()}");
                if(trade.DeliverySpeed.Contains("0"))
                {
                    trade.DeliverySpeed = "0";
                }else
                {
                    trade.DeliverySpeed = "1";
                }
                LilyTradeModel model = new LilyTradeModel(trade);
                string brokerId = "";
                string speed = "";
                if (trade.BrokerID!=null)
                {
                    brokerId =trade.BrokerID.ToString();
                }
                if (trade.DeliverySpeed != null)
                {
                    speed = trade.DeliverySpeed.ToString();
                }

                string dealType = "";
                if (trade.DealType=="bid")
                {
                    dealType = "bond_0";
                }else
                {
                    dealType = "bond_1";
                }
                returnBrokerId = 0;
                //var deliveryTimeFirst = trade.DeliveryDate.ToString("yyyy-MM-dd HH:mm:ss") ?? "";
                //var deliveryTimeSecond = trade.DeliveryDate.ToString("yyyy-MM-dd HH:mm:ss") ?? "";

                // 将 DateOnly 转换为 DateTime，时间部分设置为 00:00:00
                DateTime deliveryDateTimeFirst = new DateTime(
                    trade.DeliveryDate.Year,
                    trade.DeliveryDate.Month,
                    trade.DeliveryDate.Day,
                    0,  // 小时
                    0,  // 分钟
                    0   // 秒
                );

                int userId = trade.UserID;
                // 将 DateTime 格式化为字符串
                string formattedDeliveryTime = deliveryDateTimeFirst.ToString("yyyy-MM-dd HH:mm:ss");
                // 手动创建 JSON 对象
                var json = new JObject
                {
                    ["brokerId"] = brokerId,
                    ["deliverySpeed"] = trade.DeliverySpeed,
                    ["deliveryTime"] = formattedDeliveryTime ?? "",
                    ["deliveryTime2"] = formattedDeliveryTime ?? "",
                    ["direction"] = dealType,
                    ["price"] = trade.Price,
                    ["realTradeIdList"] = new JArray(trade.RealTradeIdList ?? new int[0]), // 转换为 JArray
                    ["remark"] = "",
                    
                    ["tscode"] = trade.TsCode ?? "",
                    ["userId"] = userId,
                    ["volume"] = trade.Volume.ToString(),
                    ["worstPrice"] = 0
      
                };

                // 将 JObject 转换为 JSON 字符串
                string jsonString = json.ToString();

                string tmp = JsonConvert.SerializeObject(model);
                using (var client = new HttpClient())
                {
                    

                    HttpContent content = new StringContent(jsonString);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserToken);
             

                    HttpResponseMessage res = client.PostAsync(string.Format($"{DataHelper.BaseConfig.HttpUrl}/realtrade/pingcang"), content).Result;
                    tmp = res.Content.ReadAsStringAsync().Result;
                    if (res.StatusCode == HttpStatusCode.OK)
                    {
                        tmp = res.Content.ReadAsStringAsync().Result;
                    }
                }
                JObject o = JObject.Parse(tmp);
                if (o["code"] == null)
                {
                    msg = "";
                    AppLog.WriteError("UserHelper" + "PingCangUserTrade(UserTrade trade, string UserToken, out int UserTradeID..." + msg);
                    return 1;
                }

                AppLog.WriteInfo("UserHelper" + "平仓PingCangUserTrade(UserTrade trade, string UserToken, out int UserTradeID..." + o);
                switch (o["code"].ToString())
                {
                    case "00000":
                        msg = o["value"]["message"].ToString();
                        trade.UserTradeID = long.Parse(o["value"]["userTradeId"].ToString());
                        returnBrokerId = int.Parse(o["value"]["brokerId"].ToString());
                        return 0;
                    case "00002":
                        msg = "";
                        return 2;
                    case "00001":
                        msg = "";
                        return 1;


                    ///重定向，功能未完成，06/21
                    case "00003":
                        msg = "";
                        return 3;
                    default:
                        msg = "";
                        return 1;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "UserHelper" + "AddUserTrade(UserTrade trade, string UserToken, out int UserTradeID..." + ex.StackTrace);
                msg = "";
                returnBrokerId = 0;
                return 1;
            }
        }



        #endregion


        #region 静态方法
        /// <summary>
        /// 查询所有违约单子
        /// </summary>
        /// <returns></returns>
        /// 
        public static async Task<WeiYueTradeResponse> SearchAllWeiYueAsync()
        {
            var startTime = DateTime.Now; // 记录方法开始时间

            try
            {
                string tmp = string.Empty;

                string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/realtrade/listweiyueTrade?userName={UserHelper.NickName}";
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                    // 发送 GET 请求并异步等待
                    HttpResponseMessage res = await client.GetAsync(apiUrl);

                    

                    if (res.IsSuccessStatusCode)
                    {
                        // 读取响应内容并异步等待
                        tmp = await res.Content.ReadAsStringAsync();
                        var WeiYueLilyTrades = JsonConvert.DeserializeObject<WeiYueTradeResponse>(tmp);
                        return WeiYueLilyTrades;
                    }
                    else
                    {
                        AppLog.WriteError($"Userhelper===违约单 请求失败.");
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"Userhelper===违约单 异常: {ex.Message}--{ex.StackTrace}");
                return null;
            }
            finally
            {
                var endTime = DateTime.Now; // 记录方法结束时间
                var duration = endTime - startTime; // 计算方法耗时
                AppLog.WriteInfo($"Userhelper===违约单 耗时: {duration.TotalMilliseconds} 毫秒");
            }
        }
        //public static WeiYueTradeResponse SearchAllWeiYue()
        //{
        //    var startTime = DateTime.Now; // 记录方法开始时间

        //    try
        //    {
        //        string tmp = string.Empty;

        //        // 构建 URL，包含 userName 参数

        //        //var testName = "Mandarava";
        //        string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/realtrade/listweiyueTrade?userName={UserHelper.NickName}";
        //        using (var client = new HttpClient())
        //        {
        //            // 设置请求头
        //            client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
        //            client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

        //            // 发送 GET 请求
        //            HttpResponseMessage res = client.GetAsync(apiUrl).Result;

        //            // 读取响应内容
        //            tmp = res.Content.ReadAsStringAsync().Result;

        //            // 检查响应状态码
        //            if (res.IsSuccessStatusCode)
        //            {
        //                // 解析 JSON 响应
        //                var WeiYueLilyTrades = JsonConvert.DeserializeObject<WeiYueTradeResponse>(tmp);

        //                return WeiYueLilyTrades;
        //                // 成功处理响应数据，例如解析 JSON 等
        //                Console.WriteLine(tmp);
        //            }
        //            else
        //            {
        //                // 处理请求失败或者错误状态码的情况
        //                Console.WriteLine($"请求失败：{res.StatusCode} - {res.ReasonPhrase}");
        //                return null;

        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        // Handle exceptions as necessary
        //        Console.WriteLine($"Error: {ex.Message}");
        //    }
        //    finally
        //    {
        //        var endTime = DateTime.Now; // 记录方法结束时间
        //        var duration = endTime - startTime; // 计算方法耗时
        //        Console.WriteLine($"Userhelper===违约单 耗时: {duration.TotalMilliseconds} 毫秒");
        //    }
        //    return null;
        //}

        /// <summary>
        /// 根据name查找所有 "未平仓单"
        /// </summary>
        /// <returns></returns>
        /// 


        public static async Task<PingCangLilyTrades> SearchAllNoPingCangOrderAsync()
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            try
            {
                string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/realtrade/listByCurrentUser";
                using (var client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                    // 发送异步 GET 请求
                    HttpResponseMessage res = await client.GetAsync(apiUrl);

                    // 检查响应状态码
                    if (res.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string tmp = await res.Content.ReadAsStringAsync();

                        // 解析 JSON 响应
                        var pingCanglilyTrades = JsonConvert.DeserializeObject<PingCangLilyTrades>(tmp);

                        stopwatch.Stop();
                        AppLog.WriteInfo($"Userhelper===未平仓单方法耗时: {stopwatch.ElapsedMilliseconds} 毫秒");

                        return pingCanglilyTrades;
                    }
                    else
                    {
                        // 处理请求失败或者错误状态码的情况
                        Console.WriteLine($"请求失败：{res.StatusCode} - {res.ReasonPhrase}");

                        stopwatch.Stop();
                        AppLog.WriteInfo($"Userhelper===未平仓单方法耗时: {stopwatch.ElapsedMilliseconds} 毫秒");

                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions as necessary
                Console.WriteLine($"Error: {ex.Message}");
                AppLog.WriteError("weiPingCanglilyTrades api失败" + ex.Message);

                stopwatch.Stop();
                AppLog.WriteInfo($"Userhelper===未平仓单方法耗时: {stopwatch.ElapsedMilliseconds} 毫秒,Error: {ex.Message}");

                return null;
            }
        }
        //public static async Task<PingCangLilyTrades> SearchAllNoPingCangOrderAsync()
        //{
        //    try
        //    {
        //        string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/realtrade/listByCurrentUser";
        //        using (var client = new HttpClient())
        //        {
        //            // 设置请求头
        //            client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
        //            client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

        //            // 发送异步 GET 请求
        //            HttpResponseMessage res = await client.GetAsync(apiUrl);

        //            // 检查响应状态码
        //            if (res.IsSuccessStatusCode)
        //            {
        //                // 读取响应内容
        //                string tmp = await res.Content.ReadAsStringAsync();

        //                // 解析 JSON 响应
        //                var pingCanglilyTrades = JsonConvert.DeserializeObject<PingCangLilyTrades>(tmp);

        //                return pingCanglilyTrades;
        //            }
        //            else
        //            {
        //                // 处理请求失败或者错误状态码的情况
        //                Console.WriteLine($"请求失败：{res.StatusCode} - {res.ReasonPhrase}");
        //                return null;
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        // Handle exceptions as necessary
        //        Console.WriteLine($"Error: {ex.Message}");
        //        AppLog.WriteError("weiPingCanglilyTrades api失败" + ex.Message);
        //        return null;
        //    }
        //}

        //public static PingCangLilyTrades SearchAllNoPingCangOrder()
        //{
        //    try
        //    {
        //        string tmp = string.Empty;

        //        // 构建 URL，包含 userName 参数

        //        var testName = "Mandarava";
        //        //string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/realtrade/listByCurrentUser?userName={UserHelper.NickName}";
        //        //string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/realtrade/listByCurrentUser";



        //        string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/realtrade/listByCurrentUser";
        //        using (var client = new HttpClient())
        //        {
        //            // 设置请求头
        //            client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
        //            client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

        //            // 发送 GET 请求
        //            HttpResponseMessage res = client.GetAsync(apiUrl).Result;

        //            // 读取响应内容
        //            tmp = res.Content.ReadAsStringAsync().Result;

        //            // 检查响应状态码
        //            if (res.IsSuccessStatusCode)
        //            {
        //                // 解析 JSON 响应
        //                var pingCanglilyTrades = JsonConvert.DeserializeObject<PingCangLilyTrades>(tmp);

        //                return pingCanglilyTrades;
        //                // 成功处理响应数据，例如解析 JSON 等
        //                Console.WriteLine(tmp);
        //            }
        //            else
        //            {
        //                // 处理请求失败或者错误状态码的情况
        //                Console.WriteLine($"请求失败：{res.StatusCode} - {res.ReasonPhrase}");
        //                return null;

        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        // Handle exceptions as necessary
        //        Console.WriteLine($"Error: {ex.Message}");
        //        AppLog.WriteError("weiPingCanglilyTrades api失败" + ex.Message);
        //    }
        //    finally
        //    {
        //        //return null;
        //    }
        //    return null;
        //}


        /// <summary>
        /// 根据name查找所有 "已平仓单"
        /// </summary>
        /// <returns></returns>
        public async static Task<List<YiPingLilyTrade>> SearchAllPingCangOrder()
        {
            var startTime = DateTime.Now; // 记录方法开始时间
            try
            {
                string tmp = string.Empty;

                // 构建 URL，包含 userName 参数

                var testName = "Mandarava";
                string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/realtrade/listFinishTrade";
                using (var client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                    // 发送 GET 请求
                    //HttpResponseMessage res = client.GetAsync(apiUrl).Result;
                    HttpResponseMessage res = await client.GetAsync(apiUrl);  // 使用 await 异步等待
                 


                    // 检查响应状态码
                    if (res.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        tmp = await res.Content.ReadAsStringAsync();  // 使用 await 异步等待
                        var jsonObj = JObject.Parse(tmp);
                        string data = jsonObj["rows"].ToString();
                        // 解析 JSON 响应
                        if(string.IsNullOrEmpty(data))
                        {
                            return null;
                        }
                        var yiPingpingCanglilyTrades = JsonConvert.DeserializeObject<List<YiPingLilyTrade>>(data);

                        return yiPingpingCanglilyTrades;
                    }
                    else
                    {
                        // 处理请求失败或者错误状态码的情况
                        Console.WriteLine($"请求失败：{res.StatusCode} - {res.ReasonPhrase}");
                        return null;

                    }
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions as necessary
                AppLog.WriteError("yiPingpingCanglilyTrades api失败" + ex.Message);
                Console.WriteLine($"Error: {ex.Message}");
            }
            finally
            {
                var endTime = DateTime.Now; // 记录方法结束时间
                var duration = endTime - startTime; // 计算方法耗时
                AppLog.WriteInfo($"Userhelper===SearchAllPingCangOrder 耗时: {duration.TotalMilliseconds} 毫秒");
            }
            return null;
        }

        /// <summary>
        /// 强平接口回调，表示消费了。
        /// </summary>
        public static async Task ConsumeQiangPingMessageAsync(string messageId)
        {

            using (var client = new HttpClient())
            {
                var message = new
                {
                    consumed = true,
                    messageId = messageId
                };
                // 序列化对象为 JSON 字符串
                var jsonMessage = System.Text.Json.JsonSerializer.Serialize(message);

                // 创建 StringContent，并设置 Content-Type 为 application/json
                HttpContent content = new StringContent(jsonMessage);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");

                client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                HttpResponseMessage res = client.PostAsync(string.Format($"{DataHelper.BaseConfig.HttpUrl}/qpinform/messageconsumed"), content).Result;
                string tmp = res.Content.ReadAsStringAsync().Result;
                if (res.StatusCode == HttpStatusCode.OK)
                {
                    tmp = res.Content.ReadAsStringAsync().Result;
                }
            }
            //try
            //{
            //    // 构建 URL，包含 userName 参数
            //    string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/qpinform/messageconsumed";

            //    using (var client = new HttpClient())
            //    {
            //        // 设置请求头
            //        client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
            //        client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

            //        // 构建 JSON 对象
            //        var message = new
            //        {
            //            consumed = true,
            //            createTime = "",
            //            duration = 0,
            //            message = "",
            //            messageId = "",
            //            startTime = "",
            //            status = 0,
            //            userId = UserHelper.UserID
            //        };


            //        // 序列化 JSON 对象
            //        var jsonContent = new StringContent(JsonConvert.SerializeObject(message), Encoding.UTF8, "application/json");

            //        // 发送 POST 请求
            //        var response = await client.PostAsync(apiUrl, jsonContent);

            //        // 确保请求成功
            //        response.EnsureSuccessStatusCode();

            //        // 读取响应内容
            //        string responseBody = await response.Content.ReadAsStringAsync();

            //        // 处理响应内容
            //        Console.WriteLine(responseBody);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    // 处理异常
            //    Console.WriteLine($"Error: {ex.Message}");
            //}
        }

        #endregion


        #region 调 用聊天接口
        public static async Task<List<LilyChatMessage>> FindAllChatMessagesAsync(int brokerId = 0, string channelId = null, int chatId = 0)
        {

            try
            {
                string tmp = string.Empty;

                // 构建 URL，包含 userName 参数

                var testName = "Mandarava";
                string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/chatMessage";
                using (var client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                    // 发送 GET 请求
                    HttpResponseMessage res = client.GetAsync(apiUrl).Result;

                    // 读取响应内容
                    tmp = res.Content.ReadAsStringAsync().Result;
                    // 解析 JSON 成为一个 JObject
                    var jsonObject = JObject.Parse(tmp);

                    // 从 JObject 中获取名为 "data" 的字段的值，并转换为字符串
                    string data = jsonObject["value"].ToString();
                    // Extract chatMessage objects


                    // Deserialize JSON directly into List<ChatMessage>
                    List<LilyChatMessage> chatMessages = JsonConvert.DeserializeObject<List<LilyChatMessage>>(data);
                    // 检查响应状态码
                    if (res.IsSuccessStatusCode)
                    {


                        return chatMessages;
                    }
                    else
                    {
                        // 处理请求失败或者错误状态码的情况
                        Console.WriteLine($"请求失败：{res.StatusCode} - {res.ReasonPhrase}");
                        return null;

                    }
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions as necessary
                Console.WriteLine($"Error: {ex.Message}");
            }
            finally
            {
                //return null;
            }
            return null;
            //    using (var client = new HttpClient())
            //    {
            //        // 创建包含请求数据的字典
            //        var data = new Dictionary<string, string>
            //{
            //    { "brokerId", brokerId.ToString() },
            //    { "channelId", channelId },
            //    { "chatId", chatId.ToString() }
            //};

            //        // 构建请求消息
            //        var request = new HttpRequestMessage(HttpMethod.Post, $"{DataHelper.BaseConfig.HttpUrl}/chatMessage/admin/findCondition")
            //        {
            //            Headers =
            //    {
            //        { "Authorization", UserHelper.Token }
            //    },
            //            Content = new FormUrlEncodedContent(data)
            //        };

            //        // 发送请求并获取响应
            //        var response = await client.SendAsync(request);
            //        var responseContent = await response.Content.ReadAsStringAsync();
            //        // 确保响应状态码为成功
            //        response.EnsureSuccessStatusCode();

            //        // 读取并返回响应内容（可根据实际需求进行处理）
            //        var responseContent = await response.Content.ReadAsStringAsync();


            //        return responseContent; // 根据实际需求返回适当的数据
            //    }
        }


        public static async Task<List<LilyChatMessage>> FindConditionChatMessagesAsync(int? brokerId = null, string? channelId = "", int chatId = 0)
        {
            try
            {
                 string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/chatMessage/findCondition";

                // 构建要发送的 JSON 数据
                var requestData = new
                {
                    brokerId = brokerId,
                    channelId = channelId,
                    chatId = UserHelper.UserID,
                };

                // 序列化 JSON 数据
                string jsonData = JsonConvert.SerializeObject(requestData);
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                using (var client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                    // 发送 POST 请求
                    HttpResponseMessage res = await client.PostAsync(apiUrl, content);

                    // 检查响应状态码
                    if (res.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string tmp = await res.Content.ReadAsStringAsync();

                        // 解析 JSON 成为一个 JObject
                        var jsonObject = JObject.Parse(tmp);

                        // 从 JObject 中获取名为 "value" 的字段的值，并转换为字符串
                        string data = jsonObject["value"].ToString();

                        // Deserialize JSON directly into List<LilyChatMessage>
                        List<LilyChatMessage> chatMessages = JsonConvert.DeserializeObject<List<LilyChatMessage>>(data);

                        return chatMessages;
                    }
                    else
                    {
                        // 处理请求失败或者错误状态码的情况
                        Console.WriteLine($"请求失败：{res.StatusCode} - {res.ReasonPhrase}");
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine($"Error: {ex.Message}");
                return null;
            }
        }


        public static async Task<LilyChatMessage> FindChatMessageByIdAsync(string messageId)
        {

            try
            {
                string tmp = string.Empty;

                // 构建 URL，包含 userName 参数
                string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/chatMessage/findCondition";

                // 构建要发送的 JSON 数据
                var requestData = new
                {
                    id = messageId
                };

                // 序列化 JSON 数据
                string jsonData = JsonConvert.SerializeObject(requestData);
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                using (var client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                    // 发送 POST 请求
                    HttpResponseMessage res = await client.PostAsync(apiUrl, content);

                    // 检查响应状态码
                    if (res.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string tmp2 = await res.Content.ReadAsStringAsync();

                        // 解析 JSON 成为一个 JObject
                        var jsonObject = JObject.Parse(tmp2);
                        // 从 JObject 中获取 "value" 字段的值
                        JArray valueArray = (JArray)jsonObject["value"];
                        // 从 JObject 中获取名为 "value" 的字段的值，并转换为字符串

                        // 确保 "value" 字段是一个数组，并且数组中有至少一个元素
                        LilyChatMessage chatMessageObject = null;
                        if (valueArray != null && valueArray.Count > 0)
                        {
                            // 从数组的第一个元素中获取 JSON 字符串
                            JObject firstItem = (JObject)valueArray[0];
                            string firstItemJson = firstItem.ToString();

                            // 反序列化 JSON 字符串到 LilyChatMessage 对象
                            chatMessageObject = JsonConvert.DeserializeObject<LilyChatMessage>(firstItemJson);

                            // 输出 chatMessage
                            return chatMessageObject;
                        }
                        string data = jsonObject["value"].ToString();

                       

                        return chatMessageObject;
                    }
                    else
                    {
                        // 处理请求失败或者错误状态码的情况
                        Console.WriteLine($"请求失败：{res.StatusCode} - {res.ReasonPhrase}");
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions as necessary
                Console.WriteLine($"Error: {ex.Message}");
            }
            finally
            {
                //return null;
            }
            return null;
            //    using (var client = new HttpClient())
            //    {
            //        // 创建包含请求数据的字典
            //        var data = new Dictionary<string, string>
            //{
            //    { "brokerId", brokerId.ToString() },
            //    { "channelId", channelId },
            //    { "chatId", chatId.ToString() }
            //};

            //        // 构建请求消息
            //        var request = new HttpRequestMessage(HttpMethod.Post, $"{DataHelper.BaseConfig.HttpUrl}/chatMessage/admin/findCondition")
            //        {
            //            Headers =
            //    {
            //        { "Authorization", UserHelper.Token }
            //    },
            //            Content = new FormUrlEncodedContent(data)
            //        };

            //        // 发送请求并获取响应
            //        var response = await client.SendAsync(request);
            //        var responseContent = await response.Content.ReadAsStringAsync();
            //        // 确保响应状态码为成功
            //        response.EnsureSuccessStatusCode();

            //        // 读取并返回响应内容（可根据实际需求进行处理）
            //        var responseContent = await response.Content.ReadAsStringAsync();


            //        return responseContent; // 根据实际需求返回适当的数据
            //    }
        }

        #endregion


        #region 调用审核相关接口
        /// <summary>
        /// 增加审核
        /// </summary>
        /// <param name="workOrder"></param>
        /// <returns></returns>
        public static async Task<bool> ReviewChatWorkOrder(ChatWorkOrder workOrder)
        {
            try
            {
               
                    using (var client = new HttpClient())
                    {
                    // 创建一个包含用户ID的匿名对象
                    var data = new
                    {
                        status = 0, // 将 status 设为整数
                        messageId = workOrder.MessageId ?? "", // 确保 messageId 是字符串，或为空字符串
                        remarks = workOrder.Remarks, // 确保 remarks 是字符串
                        type = 0, // 将 type 设为整数
                        tradeIds = string.Join(",", workOrder.TradeIds.Select(id => id.ToString())), // 将 TradeIds 转换为逗号分隔的字符串
                        weight = 100 // 将 weight 设为整数
                    };

                    var request = new HttpRequestMessage(HttpMethod.Post, $"{DataHelper.BaseConfig.HttpUrl}/chatWorkOrder");

                        request.Headers.Add("Authorization", UserHelper.Token);
                        var json = JsonConvert.SerializeObject(data);
                        var content = new StringContent(json, Encoding.UTF8, "application/json");

                        request.Content = content;

                        var response = await client.SendAsync(request);
                    //var tmp = response.Content.ReadAsStringAsync().Result;
                        var responseContent = await response.Content.ReadAsStringAsync();
                    // 解析 JSON 响应
                    var jsonResponse = JObject.Parse(responseContent);

                    // 获取 code 字段的值
                    var code = jsonResponse["code"]?.ToString();
                    if(code =="00000")
                    {
                        return true;
                    }else
                    {
                        return false;
                    }
                    // 检查请求是否成功
                    response.EnsureSuccessStatusCode();
                         return true;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("SaveMessageToLily异常" + ex.Message + ex.StackTrace);
                return false;
            }

        }


        /// <summary>
        /// 查询审核
        /// </summary>
        /// <param name="workOrder"></param>
        /// <returns></returns>
        public static async Task<List<LilyChatWorkOrder>> GetChatWorkOrders()
        {
            try
            {
                string tmp = string.Empty;

                // 构建 URL，包含 userName 参数
                string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/chatWorkOrder";
                using (var client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                    // 发送 GET 请求
                    HttpResponseMessage res = client.GetAsync(apiUrl).Result;

                    //// 读取响应内容
                    //tmp = res.Content.ReadAsStringAsync().Result;
                    //// 解析 JSON 成为一个 JObject
                    //var jsonObject = JObject.Parse(tmp);

                    //// 从 JObject 中获取名为 "data" 的字段的值，并转换为字符串
                    //string data = jsonObject["value"].ToString();
                    // Extract chatMessage objects


                    // Deserialize JSON directly into List<ChatMessage>
                   
                    // 检查响应状态码
                    if (res.IsSuccessStatusCode)
                    {

                        // 读取响应内容
                        string tmp2 = await res.Content.ReadAsStringAsync();
                        // 解析 JSON 成为一个 JObject
                        var jsonObject = JObject.Parse(tmp2);
                        string data = jsonObject["value"].ToString();
                        // 解析 JSON 成为 JArray
                        List<LilyChatWorkOrder> chatWorkOrders = JsonConvert.DeserializeObject<List<LilyChatWorkOrder>>(data);



                        return chatWorkOrders;
                    }
                    else
                    {
                        // 处理请求失败或者错误状态码的情况
                        Console.WriteLine($"请求失败：{res.StatusCode} - {res.ReasonPhrase}");
                        return null;

                    }
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions as necessary
                Console.WriteLine($"Error: {ex.Message}");
                AppLog.WriteError("GetChatWorkOrders找审核单失败" + ex.Message + ex.StackTrace);
            }
            finally
            {
                //return null;
            }
            return null;

        }
        #endregion

        #region 调用询价相关接口
        public static async Task<List<LilyTrade>> FindAllXunJiaOrdersAsync(int brokerId = 0, string channelId = null, int chatId = 0)
        {

            try
            {
                string tmp = string.Empty;

                // 构建 URL，包含 userName 参数
                string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/usertrade/listByCurrentUser";
                using (var client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                    // 发送 GET 请求
                    HttpResponseMessage res = await client.GetAsync(apiUrl);

                    
                    // 检查响应状态码
                    if (res.IsSuccessStatusCode)
                    {

                        // 读取响应内容
                        tmp = await res.Content.ReadAsStringAsync();  // 使用 await 异步等待
                        // 解析 JSON 成为一个 JObject
                        var jsonObject = JObject.Parse(tmp);

                        // 从 JObject 中获取名为 "data" 的字段的值，并转换为字符串
                        string data = jsonObject["rows"].ToString();
                        // Extract chatMessage objects


                        // Deserialize JSON directly into List<ChatMessage>
                        List<LilyTrade> userTrades = JsonConvert.DeserializeObject<List<LilyTrade>>(data);
                        return userTrades;
                    }
                    else
                    {
                        // 处理请求失败或者错误状态码的情况
                        AppLog.WriteError($"FindAllXunJiaOrdersAsync请求失败：{res.StatusCode} - {res.ReasonPhrase}");
                        return null;

                    }
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions as necessary
                //Console.WriteLine($"Error: {ex.Message}");
                AppLog.WriteError("FindAllXunJiaOrdersAsync找到询价单失败"+ex.Message+ex.StackTrace);
            }
            finally
            {
                //return null;
            }
            return null;
        }

        public bool CancelUserTrade(long userTradeID, string UserToken, out string msg, out string returnMsg, int i = 0)
        {
            msg = "";
            HttpWebRequest request;

            StreamReader myStreamReader;
            string httpUrl;
            if (i == 1)
            {
                httpUrl = DataHelper.BaseConfig.LilyHttpUrl;
            }
            else
            {
                httpUrl = DataHelper.BaseConfig.HttpUrl;
            }

            AppLog.WriteInfo("客户端原生撤单trade" + "CancelUserTrade，UserTradeId是" + userTradeID.ToString());
            request = (HttpWebRequest)WebRequest.Create($"{httpUrl}/usertrade/cancelrequest" + "?usertradeId=" + userTradeID.ToString());
            request.Method = "Post";
            request.Accept = "application/json";
            request.UserAgent = "BondHelper";
            request.ContentType = "application/json; charset=utf-8";
            request.Headers.Add("Authorization", UserToken);
            request.ProtocolVersion = HttpVersion.Version11;
            request.Timeout = TimeOut;
            request.ServicePoint.Expect100Continue = false;
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                try
                {

                    myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    string loginModel = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myStreamReader.Dispose();
                    JObject o = JObject.Parse(loginModel);
                    AppLog.WriteInfo("UserHelper" + "Lily返回撤单" + o.ToString());
                    if (o["code"].ToString() == "00000")
                    {
                        msg = o["value"]["message"].ToString();
                        returnMsg = msg;
                        return true;
                    }
                    else
                    {
                        msg = o["message"].ToString();
                        returnMsg = msg;
                        return false;
                    }

                }

                catch (Exception ex)
                {
                    AppLog.WriteError(ex.Message + "UserHelper" + "CancelUserTrade" + ex.StackTrace);
                    returnMsg = msg;
                    return false;
                }
                finally
                {
                    response.Close();
                    response.Dispose();
                }
            }
        }


        /// <summary>
        /// 找到可撤询价单
        /// </summary>
        /// <param name="brokerId"></param>
        /// <param name="channelId"></param>
        /// <param name="chatId"></param>
        /// <returns></returns>
        /// 
        public static List<LilyTrade> FindKeCheXunJiaOrders(int brokerId = 0, string channelId = null, int chatId = 0)
        {
            try
            {
                string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/usertrade/listKeche";
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                    HttpResponseMessage res = client.GetAsync(apiUrl).GetAwaiter().GetResult();
                    if (res.IsSuccessStatusCode)
                    {
                        string tmp = res.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                        var jsonObject = JObject.Parse(tmp);
                        string data = jsonObject["rows"].ToString();
                        List<LilyTrade> userTrades = JsonConvert.DeserializeObject<List<LilyTrade>>(data);
                        return userTrades;
                    }
                    else
                    {
                        Console.WriteLine($"请求失败：{res.StatusCode} - {res.ReasonPhrase}");
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"FindKeCheXunJiaOrders找到可撤询价单Error: {ex.Message}");
                return null;
            }
        }

        //public static async Task<List<LilyTrade>> FindKeCheXunJiaOrdersAsync(int brokerId = 0, string channelId = null, int chatId = 0)
        //{
        //    try
        //    {
        //        string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/usertrade/listKeche";
        //        using (var client = new HttpClient())
        //        {
        //            client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
        //            client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

        //            HttpResponseMessage res = await client.GetAsync(apiUrl);
        //            if (res.IsSuccessStatusCode)
        //            {
        //                string tmp = await res.Content.ReadAsStringAsync();
        //                var jsonObject = JObject.Parse(tmp);
        //                string data = jsonObject["rows"].ToString();
        //                List<LilyTrade> userTrades = JsonConvert.DeserializeObject<List<LilyTrade>>(data);
        //                return userTrades;
        //            }
        //            else
        //            {
        //                Console.WriteLine($"请求失败：{res.StatusCode} - {res.ReasonPhrase}");
        //                return null;
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteError($"FindKeCheXunJiaOrdersAsync找到可撤询价单Error: {ex.Message}");
        //        return null;
        //    }
        //}

        public static async Task<UserTrade> LoadTradesAndFindLatestAsync(string BondNumber)
        {
            var tradesNew = UserHelper.FindKeCheXunJiaOrders(); 
            if (tradesNew == null) return null;

            var tradeModels = tradesNew.Select(trade => new UserTrade
            {
                BrokerID = trade.BrokerId,
                Status = trade.Status,
                Price = (decimal)trade.Price,
                Volume = int.Parse(trade.Volume),
                OnHoldVolume = int.Parse(trade.RestVolume),
                TsCode = trade.Tscode,
                Time = trade.CreateTime,
                DealType = trade.Direction == "bond_0" ? "买入" : (trade.Direction == "bond_1" ? "卖出" : "未知"),
                UserTradeID = trade.UserTradeId,
                ChannelID = trade.ChannelId,
                DeliveryDate = DateOnly.FromDateTime(trade.DeliveryTime),
                DeliverySpeed = trade.DeliverySpeed,
                Target = trade.Target
            }).ToList();

            var tradeList = tradeModels.ToObservableCollection();
            return tradeList
                .Where(o => o.TsCode == BondNumber)
                .OrderByDescending(o => o.Time)
                .FirstOrDefault();
        }


        /// <summary>
        /// 获取最大可买可卖量
        /// </summary>
        /// <param name="tscode"></param>
        public static async Task<int[]> GetMaxBidVolumeAsync(string tscode)
        {
            string url = $"{DataHelper.BaseConfig.HttpUrl}/tradeamountlimit/getMaxBidByTscode?tscode={tscode}";

            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);
                    HttpResponseMessage response = await client.GetAsync(url);

                    if (response.IsSuccessStatusCode)
                    {
                        string content = await response.Content.ReadAsStringAsync();
                        JObject json = JObject.Parse(content);

                        if (json["code"]?.ToString() == "00000")
                        {
                            JArray values = (JArray)json["value"];
                            int[] maxBidVolumes = values.ToObject<int[]>();
                            return maxBidVolumes;
                        }
                        else
                        {
                            AppLog.WriteError("获取最大可买可卖量异常");
                        }
                    }
                    else
                    {
                        AppLog.WriteError("获取最大可买可卖量超时");
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("获取最大可买可卖量异常"+ex.Message);

            }

            return null;
        }


        //public static async Task<List<LilyTrade>> FindKeCheXunJiaOrdersAsync(int brokerId = 0, string channelId = null, int chatId = 0)
        //{

        //    try
        //    {
        //        string tmp = string.Empty;

        //        // 构建 URL，包含 userName 参数
        //        string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/usertrade/listKeche";
        //        using (var client = new HttpClient())
        //        {
        //            // 设置请求头
        //            client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
        //            client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

        //            // 发送 GET 请求
        //            HttpResponseMessage res = client.GetAsync(apiUrl).Result;

        //            // 读取响应内容
        //            tmp = res.Content.ReadAsStringAsync().Result;
        //            // 解析 JSON 成为一个 JObject
        //            var jsonObject = JObject.Parse(tmp);

        //            // 从 JObject 中获取名为 "data" 的字段的值，并转换为字符串
        //            string data = jsonObject["rows"].ToString();
        //            // Extract chatMessage objects


        //            // Deserialize JSON directly into List<ChatMessage>
        //            List<LilyTrade> userTrades = JsonConvert.DeserializeObject<List<LilyTrade>>(data);
        //            // 检查响应状态码
        //            if (res.IsSuccessStatusCode)
        //            {


        //                return userTrades;
        //            }
        //            else
        //            {
        //                // 处理请求失败或者错误状态码的情况
        //                Console.WriteLine($"请求失败：{res.StatusCode} - {res.ReasonPhrase}");
        //                return null;

        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        // Handle exceptions as necessary
        //        Console.WriteLine($"Error: {ex.Message}");
        //    }
        //    finally
        //    {
        //        //return null;
        //    }
        //    return null;
        //}



        /// <summary>
        /// 获取某个询价单详情
        /// </summary>
        /// <param name="usertradeId"></param>
        /// <returns></returns>
        public static async Task<LilyTrade> GetTradeByTradeIdApiAsync(int usertradeId)
        {
            var requestUrl = $"{DataHelper.BaseConfig.HttpUrl}/usertrade/listById?usertradeId={usertradeId}";

            var request = (HttpWebRequest)WebRequest.Create(requestUrl);
            request.Method = "GET";
            request.Accept = "application/json";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36";
            request.ContentType = "application/json; charset=utf-8";
            request.Headers.Add("Authorization", UserHelper.Token);
            request.KeepAlive = true;
            request.Timeout = 10000;  // 设置超时时间

            try
            {
                using (var response = (HttpWebResponse)await request.GetResponseAsync())
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        using (var reader = new StreamReader(responseStream, Encoding.UTF8))
                        {

                            var responseText = await reader.ReadToEndAsync();

                            // Parse the JSON string into a JObject
                            var jsonObject = JObject.Parse(responseText);

                            // Extract the value associated with the "value" key
                            var data = jsonObject["value"].ToString();

                            // Deserialize JSON directly into LilyTrade object
                            LilyTrade trade = JsonConvert.DeserializeObject<LilyTrade>(data);

                            return trade;
                            // 可以根据需要处理响应数据
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                AppLog.WriteError("GetTradeByTradeIdApiAsync异常" + ex.StackTrace + ex.Message);
                return null;
            }
            catch (Exception ex)
            {
                AppLog.WriteError("GetTradeByTradeIdApiAsync异常" + ex.StackTrace + ex.Message);
                return null;
            }
        }


        /// <summary>
        /// 获取某个询价单详情(拿价格）
        /// </summary>
        /// <param name="usertradeId"></param>
        /// <returns></returns>
        public static async Task<Tsinfo> GetTscodeInfo(string tsCode)
        {
            var requestUrl = $"{DataHelper.BaseConfig.HttpUrl}/tsinfo/getByCode?tscode={tsCode}";

            var request = (HttpWebRequest)WebRequest.Create(requestUrl);
            request.Method = "GET";
            request.Accept = "application/json";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36";
            request.ContentType = "application/json; charset=utf-8";
            request.Headers.Add("Authorization", UserHelper.Token);
            request.KeepAlive = true;
            request.Timeout = 10000;  // 设置超时时间

            try
            {
                using (var response = (HttpWebResponse)await request.GetResponseAsync())
                {
                    using (var responseStream = response.GetResponseStream())
                    {
                        using (var reader = new StreamReader(responseStream, Encoding.UTF8))
                        {

                            var responseText = await reader.ReadToEndAsync();

                            // Parse the JSON string into a JObject
                            var jsonObject = JObject.Parse(responseText);

                            // Extract the value associated with the "value" key
                            var data = jsonObject["value"].ToString();

                            // Deserialize JSON directly into LilyTrade object
                            Tsinfo tsInfo = JsonConvert.DeserializeObject<Tsinfo>(data);

                            return tsInfo;
                            // 可以根据需要处理响应数据
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                AppLog.WriteError("GetTradeByTradeIdApiAsync异常" + ex.StackTrace + ex.Message);
                return null;
            }
            catch (Exception ex)
            {
                AppLog.WriteError("GetTradeByTradeIdApiAsync异常" + ex.StackTrace + ex.Message);
                return null;
            }
        }

        private static JsonSerializerSettings settings = new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            MissingMemberHandling = MissingMemberHandling.Ignore
        };
        /// <summary>
        /// 查询交易信息
        /// </summary>
        /// <param name="tsCode"></param>
        /// <param name="dtStart"></param>
        /// <param name="dtEnd"></param>
        /// <param name="days"></param>
        /// <param name="noForward"></param>
        /// <returns></returns>
        public static List<TradeHistoryRow> GetTradeHistories(string TsCode, DateOnly dtStart, DateOnly dtEnd, bool NoForward = false)
        {
            List<TradeHistoryRow> tmpTrades = new List<TradeHistoryRow>();
            try
            {
                string tmp = "";
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);
                    client.Timeout = new TimeSpan(0, 0, 10);
                    NoForward = !NoForward;
                    //string forward = "true";
                    //if(NoForward)
                    //{
                    //    forward = "true";
                    //}else
                    //{
                    //    forward = "false";
                    //}

                    //tmp = $"{{\"tscode\":\"{TsCode}\", \"dtStart\":\"{dtStart:yyyy-MM-dd HH:mm:ss}\", \"dtEnd\":\"{dtEnd:yyyy-MM-dd HH:mm:ss}\",\"noForward\":true}}";
                    tmp = $"{{\"tscode\":\"{TsCode}\", \"dtStart\":\"{dtStart:yyyy-MM-dd}\", \"dtEnd\":\"{dtEnd:yyyy-MM-dd}\",\"noForward\":\"{NoForward.ToString().ToLower()}\"}}";

                    HttpContent content = new StringContent(tmp);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36");
                    HttpResponseMessage res = client.PostAsync(string.Format($"{DataHelper.BaseConfig.HttpUrl}/tradehistory/list"), content).Result;
                    if (res.StatusCode == HttpStatusCode.OK)
                    {
                        tmp = res.Content.ReadAsStringAsync().Result;
                    }
                }
               
                JObject o = JObject.Parse(tmp);
                
                tmpTrades = JsonConvert.DeserializeObject<List<TradeHistoryRow>>(o["value"].ToString(), settings);
               
                tmpTrades = tmpTrades.Where(x => x.Forward == false).OrderByDescending(x => x.TradeDate).ToList();
     
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message+"Userhelper"+ "GetTradeHistories"+ex.StackTrace);
            }
            return tmpTrades;
        }


        public static async Task<List<TradeHistoryRow>> GetTradeHistoriesAsync(string TsCode, DateOnly dtStart, DateOnly dtEnd,int days, bool NoForward = false)
        {
            List<TradeHistoryRow> tmpTrades = new List<TradeHistoryRow>();
            try
            {

                //dtStart = dtStart.AddDays(-1);
                dtEnd = dtEnd.AddDays(1);
                //string tmp = $"{{\"tscode\":\"{TsCode}\", \"dtStart\":\"{dtStart:yyyy-MM-dd}\", \"dtEnd\":\"{dtEnd:yyyy-MM-dd}\", \"days\":\"{days}\",\"noForward\":\"{NoForward.ToString().ToLower()}\"}}";
                string tmp = $"{{\"tscode\":\"{TsCode}\", \"dtStart\":\"{dtStart:yyyy-MM-dd}\", \"dtEnd\":\"{dtEnd:yyyy-MM-dd}\",\"noForward\":\"{NoForward.ToString().ToLower()}\"}}";

                HttpContent content = new StringContent(tmp);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);
                    client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36");
                    //client.Timeout = TimeSpan.FromSeconds(10);
                    client.Timeout = TimeSpan.FromMinutes(2); // 设置超时时间为 2 分钟

                    HttpResponseMessage res = await client.PostAsync($"{DataHelper.BaseConfig.HttpUrl}/tradehistory/list", content);
                    if (res.StatusCode == HttpStatusCode.OK)
                    {
                        tmp = await res.Content.ReadAsStringAsync();
                    }
                }
                // 确保 tmp 不为 null
                if (string.IsNullOrEmpty(tmp))
                {
                    return null;
                }
                JObject o = JObject.Parse(tmp);
                if (o["value"] == null)
                {
                    return null;
                }
                tmpTrades = JsonConvert.DeserializeObject<List<TradeHistoryRow>>(o["value"].ToString(), settings);

                // 按时间倒序排序
                //tmpTrades = tmpTrades.OrderBy(t => t.TradeDate).ToList();
                // 应用转换方法
                // 使用 Parallel.ForEach 进行并行处理
                Parallel.ForEach(tmpTrades, trade =>
                {
                    trade.SettleSpeed = DeliverySpeedConverter.ConvertToSpeed(trade.SettleSpeed);
                });
                //if (tmpTrades.Count > 0)
                //{
                //    // 使用并行处理来优化替换 SettleSpeed 字段的操作
                //    Parallel.ForEach(tmpTrades, trade =>
                //    {
                //        trade.SettleSpeed = DeliverySpeedConverter.ConvertToSpeed(trade.SettleSpeed);
                //    });
                //}

                //tmpTrades = tmpTrades.Where(x => !x.Forward).OrderByDescending(x => x.TradeDate).ToList();
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"{ex.Message} UserHelper.GetTradeHistories {ex.StackTrace}");
            }
            return tmpTrades;
        }
        //public static async Task<List<TradeHistoryRow>> GetTradeHistoriesAsync(string TsCode, DateOnly dtStart, DateOnly dtEnd, bool NoForward = false)
        //{
        //    List<TradeHistoryRow> tmpTrades = new List<TradeHistoryRow>();
        //    try
        //    {
        //        dtEnd = dtEnd.AddDays(1);
        //        var requestBody = new
        //        {
        //            tscode = TsCode,
        //            dtStart = dtStart.ToString("yyyy-MM-dd"),
        //            dtEnd = dtEnd.ToString("yyyy-MM-dd"),
        //            noForward = NoForward.ToString().ToLower()
        //        };

        //        string jsonContent = JsonConvert.SerializeObject(requestBody);
        //        using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
        //        {
        //            using (var client = HttpClientFactory.Client)
        //            {
        //                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", UserHelper.Token);

        //                HttpResponseMessage response = await client.PostAsync($"{DataHelper.BaseConfig.HttpUrl}/tradehistory/list", content);

        //                if (response.IsSuccessStatusCode)
        //                {
        //                    string responseBody = await response.Content.ReadAsStringAsync();
        //                    var responseObject = JsonConvert.DeserializeObject<JObject>(responseBody);
        //                    var tradeHistoryRows = responseObject["value"]?.ToString();
        //                    tmpTrades = JsonConvert.DeserializeObject<List<TradeHistoryRow>>(tradeHistoryRows, settings);
        //                }
        //                else
        //                {
        //                    AppLog.WriteError($"Error: {response.ReasonPhrase}");
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteError($"{ex.Message} UserHelper.GetTradeHistories {ex.StackTrace}");
        //    }
        //    return tmpTrades;
        //}
        #endregion



        /// <summary>
        /// 获取债券白名单
        /// </summary>
        /// <returns></returns>
        public static List<string> GetTscodeWhiteList()
        {
            try
            {
                string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/api/tscodewhitelist";
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                    // 发送 GET 请求并获取响应内容
                    string responseContent = client.GetStringAsync(apiUrl).Result;

                    // 使用 JObject 解析 JSON 数据
                    var json = JObject.Parse(responseContent);

                    // 提取 code 和 value 字段
                    var code = json["code"]?.ToString();
                    var value = json["value"]?.ToObject<List<string>>();

                    // 检查 code 是否为 "00000" 并返回 value
                    if (code == "00000")
                    {
                        return value ?? new List<string>();
                    }
                    else
                    {
                        return new List<string>(); // 或者返回 null，根据需求选择
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"GetTscodeWhiteList异常,{ex.Message}--{ex.StackTrace}");
                return null;
            }
        }
        /// <summary>
        /// 获取所有可用中介
        /// </summary>
        /// <returns></returns>
        public static async Task<List<ChatReceiver>> GetChatReceiversAsync(int UserID = 0)
        {
            try
            {
                string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/chatReceiver";
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                    // 发送 GET 请求并获取响应内容
                    string responseContent = client.GetStringAsync(apiUrl).Result;

                    // 使用 JObject 解析 JSON 数据
                    var json = JObject.Parse(responseContent);

                    // 提取 code 和 value 字段
                    var code = json["code"]?.ToString();
                    var value = json["value"]?.ToObject<List<ChatReceiver>>();

                    // 检查 code 是否为 "00000" 并返回 value
                    if (code == "00000")
                    {
                        return value ?? new List<ChatReceiver>();
                    }
                    else
                    {
                        return new List<ChatReceiver>(); // 或者返回 null，根据需求选择
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "Userhelper" + "GetChatReceivers" + ex.StackTrace);
                return new List<ChatReceiver>(); // 处理异常情况并返回空列表
            }
        }


        /// <summary>
        /// 获取本机Mac地址
        /// </summary>
        /// <returns></returns>
        public string GetMacAddress()
        {
            const int MIN_MAC_ADDR_LENGTH = 12;
            string macAddress = string.Empty;
            long maxSpeed = -1;

            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (nic.OperationalStatus != OperationalStatus.Up)
                {
                    continue;
                }
                string tempMac = nic.GetPhysicalAddress().ToString();
                if (nic.Speed > maxSpeed &&
                    !string.IsNullOrEmpty(tempMac) &&
                    tempMac.Length >= MIN_MAC_ADDR_LENGTH)
                {
                    maxSpeed = nic.Speed;
                    macAddress = tempMac;
                }
            }
            string lowerMac = macAddress.ToLower();
            return lowerMac;
        }

        /// <summary>
        /// 获取债券明细
        /// </summary>
        /// <param name="tsCode"></param>
        /// <returns></returns>
        public async static Task<TSInfoRow> GetBondByCode(string tsCode)
        {
            try
            {
                string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/tsinfo/getByCode?tscode={tsCode}";
                using (var client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                    // 发送异步 GET 请求
                    HttpResponseMessage res = await client.GetAsync(apiUrl);

                    // 检查响应状态码
                    if (res.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string tmp = await res.Content.ReadAsStringAsync();

                        // 解析 JSON 响应
                        var jsonResponse = JsonConvert.DeserializeObject<dynamic>(tmp);

                        // 检查返回的 code 是否为 "00000"
                        if (jsonResponse.code == "00000")
                        {
                            // 获取 value 对象
                            var value = jsonResponse.value.ToString();

                            // 解析 value 对象为 TSInfoRow 类型
                            var tsInfoRow = new TSInfoRow
                            { tsCode = tsCode };

                            return tsInfoRow;
                        }
                        else
                        {
                            // 如果 code 不是 "00000"，记录错误日志
                            AppLog.WriteError($"GetBondByCode: API 返回错误 code - {jsonResponse.code}");
                            return null;
                        }
                    }
                    else
                    {
                        // 响应不成功，记录错误日志
                        AppLog.WriteError($"GetBondByCode: HTTP 请求失败，状态码 - {res.StatusCode}");
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                // 捕获异常并记录错误日志
                AppLog.WriteError("Userhelper=GetBondByCode异常: " + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 获取所有用户信息
        /// </summary>
        /// <returns></returns>
        public async static Task<List<LilyUserInfo>> GetAllUserInfo()
        {
            try
            {
                string apiUrl = $"{DataHelper.BaseConfig.HttpUrl}/system/user/list";
                using (var client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Add("User-Agent", "BondHelper");
                    client.DefaultRequestHeaders.Add("Authorization", UserHelper.Token);

                    // 发送异步 GET 请求
                    HttpResponseMessage res = await client.GetAsync(apiUrl);

                    // 检查响应状态码
                    if (res.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string tmp = await res.Content.ReadAsStringAsync();

                        // 解析 JSON 响应

                        var jsonResponse = JsonConvert.DeserializeObject<LilyUserList>(tmp);

                        // 检查返回的 code 是否为 "00000"
                        if (jsonResponse.Code == "200")
                        {
                            // 获取 value 对象



                            return jsonResponse.Rows;
                        }
                        else
                        {
                            // 如果 code 不是 "00000"，记录错误日志
                            AppLog.WriteError($"GetAllUserInfo: API 返回错误 code");
                            return null;
                        }
                    }
                    else
                    {
                        // 响应不成功，记录错误日志
                        AppLog.WriteError($"GetBondByCode: HTTP 请求失败，状态码 - {res.StatusCode}");
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                // 捕获异常并记录错误日志
                AppLog.WriteError("Userhelper=GetBondByCode异常: " + ex.Message);
                return null;
            }
        }

        public static string GetLXWServerIP()
        {
            //return "172.16.10.124";
            //return "127.0.0.1";
            return "180.184.174.79";
        }

        public static int GetLXWServerPort()
        {
            return 38888;
        }
    }

    public static class HttpClientFactory
    {
        private static readonly HttpClient _client = new HttpClient
        {
            Timeout = TimeSpan.FromSeconds(10)
        };

        static HttpClientFactory()
        {
            _client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
            _client.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36");
        }

        public static HttpClient Client => _client;
    }


    #region 对接lily接口的实体类

    public class LilyUserInfo
    {
        public string? SearchValue { get; set; }
        public string? CreateBy { get; set; }
        public string? CreateTime { get; set; }
        public string? UpdateBy { get; set; }
        public string? UpdateTime { get; set; }
        public string? Remark { get; set; }
        public Dictionary<string, string>? Params { get; set; }
        public string? UserType { get; set; }
        public int UserId { get; set; }
        public string? DeptId { get; set; }
        public string? UserName { get; set; }
        public string? NickName { get; set; }
        public string? Email { get; set; }
        public string? Phonenumber { get; set; }
        public string? Sex { get; set; }
        public string? Avatar { get; set; }
        public string? Salt { get; set; }
        public string? Status { get; set; }
        public string? DelFlag { get; set; }
        public string? LoginIp { get; set; }
        public string? LoginDate { get; set; }
        public string? Hwinfo { get; set; }
        public List<string>? Roles { get; set; }
        public string? RoleIds { get; set; }
        public string? PostIds { get; set; }
        public bool Admin { get; set; }
    }

    public class LilyUserList
    {
        public int Total { get; set; }
        public List<LilyUserInfo>? Rows { get; set; }

        public string Code { get; set; }
    }

    public class LilyTrade
    {
        [JsonProperty("realTradeId")]
        public int? RealTradeId { get; set; }

        [JsonProperty("userTradeId")]
        public int UserTradeId { get; set; }

        [JsonProperty("direction")]
        public string Direction { get; set; }

        [JsonProperty("tscode")]
        public string Tscode { get; set; }

        [JsonProperty("volume")]
        public string Volume { get; set; }

        [JsonProperty("restVolume")]
        public string RestVolume { get; set; }

        [JsonProperty("price")]
        public decimal? Price { get; set; }

        [JsonProperty("worstPrice")]
        public decimal? WorstPrice { get; set; }

        [JsonProperty("remark")]
        public string Remark { get; set; }

        [JsonProperty("userId")]
        public int UserId { get; set; }

        [JsonProperty("createBy")]
        public int CreateBy { get; set; }

        [JsonProperty("createTime")]
        public DateTime CreateTime { get; set; }

        [JsonProperty("updateTime")]
        public DateTime UpdateTime { get; set; }

        [JsonProperty("tradeuser")]
        public string? Tradeuser { get; set; }

        [JsonProperty("createuser")]
        public string? Createuser { get; set; }

        [JsonProperty("yanjiuyuanName")]
        public string? YanjiuyuanName { get; set; }

        [JsonProperty("tradeNum")]
        public string? TradeNum { get; set; }

        [JsonProperty("relativeNum")]
        public string? RelativeNum { get; set; }

        [JsonProperty("sourceNum")]
        public string? SourceNum { get; set; }

        [JsonProperty("isYouxian")]
        public int IsYouxian { get; set; }

        [JsonProperty("youxianLevel")]
        public int YouxianLevel { get; set; }

        [JsonProperty("deliveryTime")]
        public DateTime DeliveryTime { get; set; }

        [JsonProperty("deliverySpeed")]
        public string DeliverySpeed { get; set; }

        [JsonProperty("forward")]
        public bool Forward { get; set; }

        [JsonProperty("status")]
        public int Status { get; set; }

        [JsonProperty("orderType")]
        public string OrderType { get; set; }

        [JsonProperty("realVolume")]
        public string? RealVolume { get; set; }

        [JsonProperty("children")]
        public List<LilyTrade>? Children { get; set; }

        [JsonProperty("parentId")]
        public int? ParentId { get; set; }

        [JsonProperty("realDeliveryTime")]
        public DateTime? RealDeliveryTime { get; set; }

        [JsonProperty("realPrice")]
        public decimal? RealPrice { get; set; }

        [JsonProperty("tradeTime")]
        public DateTime? TradeTime { get; set; }

        [JsonProperty("gundanFinished")]
        public bool GundanFinished { get; set; }

        [JsonProperty("xunjiaTime")]
        public DateTime? XunjiaTime { get; set; }

        [JsonProperty("xunjiaDate")]
        public DateTime? XunjiaDate { get; set; }

        [JsonProperty("tradeDate")]
        public DateTime? TradeDate { get; set; }

        [JsonProperty("tradeTime2")]
        public DateTime? TradeTime2 { get; set; }

        [JsonProperty("channelId")]
        public string ChannelId { get; set; }

        [JsonProperty("brokerId")]
        public int BrokerId { get; set; }

        [JsonProperty("target")]
        public string Target { get; set; }

        [JsonProperty("qiangpingId")]
        public string QiangpingId { get; set; }

    }

    public class LilyTrades
    {
        [JsonProperty("total")]
        public int Total { get; set; }

        [JsonProperty("rows")]
        public List<LilyTrade> TradeRows { get; set; }
    }



    #region lily 平仓相关实体类
    public class YiPingLilyTrade
    {
        public int RealTradeId { get; set; }
        public object FtId { get; set; }
        public string Direction { get; set; }
        public string Tscode { get; set; }
        public string Volume { get; set; }
        public int Status { get; set; }
        public int JiaogeStatus { get; set; }
        public string TradeNum { get; set; }
        public string UserTradeNum { get; set; }
        public double Price { get; set; }
        public string Remark { get; set; }
        public int CreateBy { get; set; }
        public string Tradeuser { get; set; }
        public int YanjiuyuanId { get; set; }
        public string YanjiuyuanName { get; set; }
        public string CreateTime { get; set; }
        public object UpdateTime { get; set; }
        public string DeliveryTime { get; set; }
        public string DeliverySpeed { get; set; }
        public double? Profit { get; set; }
        public string FinishCode { get; set; }
        public object CounterParty { get; set; }
        public object ContactPerson { get; set; }
        public object ContactType { get; set; }
        public string RelativeNum { get; set; }
        public object ParentId { get; set; }
        public object ChengjiaoAmount { get; set; }
        public object TradeTime { get; set; }
        public object TradeDate { get; set; }

        //手续费
        public decimal? Fee { get; set; }
        public decimal? RealFee { get; set; }

        [JsonIgnore]
        public bool Flag { get; set; } = false; //标记是否属于一组的
    }


    public class PingCangLilyTrade
    {
        [JsonProperty("realTradeId")]
        public int? RealTradeId { get; set; }

        [JsonProperty("userTradeId")]
        public int? UserTradeId { get; set; }

        [JsonProperty("direction")]
        public string Direction { get; set; }

        [JsonProperty("tscode")]
        public string Tscode { get; set; }

        [JsonProperty("status")]
        public int? Status { get; set; }

        [JsonProperty("jiaogeStatus")]
        public int? JiaogeStatus { get; set; }

        [JsonProperty("volume")]
        public string Volume { get; set; }

        [JsonProperty("restVolume")]
        public int? RestVolume { get; set; }

        [JsonProperty("tradeNum")]
        public string TradeNum { get; set; }

        [JsonProperty("userTradeNum")]
        public string UserTradeNum { get; set; }

        [JsonProperty("price")]
        public decimal? Price { get; set; }

        [JsonProperty("remark")]
        public string Remark { get; set; }

        [JsonProperty("createBy")]
        public int? CreateBy { get; set; }

        [JsonProperty("tradeuser")]
        public string Tradeuser { get; set; }

        [JsonProperty("yanjiuyuanId")]
        public int? YanjiuyuanId { get; set; }

        [JsonProperty("yanjiuyuanName")]
        public string YanjiuyuanName { get; set; }

        [JsonProperty("createTime")]
        public DateTime? CreateTime { get; set; }

        [JsonProperty("tradeDate")]
        public DateTime? TradeDate { get; set; }

        [JsonProperty("tradeTime")]
        public DateTime? TradeTime { get; set; }

        [JsonProperty("updateTime")]
        public DateTime? UpdateTime { get; set; }

        [JsonProperty("deliveryTime")]
        public DateTime? DeliveryTime { get; set; }

        [JsonProperty("dicangDeliveryTime")]
        public DateTime? DicangDeliveryTime { get; set; }

        [JsonProperty("dicangTradeTime")]
        public DateTime? DicangTradeTime { get; set; }

        [JsonProperty("deliverySpeed")]
        public string DeliverySpeed { get; set; }

        [JsonProperty("floatProfit")]
        public decimal? FloatProfit { get; set; }

        [JsonProperty("relativeNum")]
        public string RelativeNum { get; set; }

        [JsonProperty("sourceNum")]
        public string SourceNum { get; set; }

        [JsonProperty("roleNum")]
        public string RoleNum { get; set; }

        [JsonProperty("sort")]
        public string Sort { get; set; }

        [JsonProperty("counterParty")]
        public string CounterParty { get; set; }

        [JsonProperty("contactPerson")]
        public string ContactPerson { get; set; }

        [JsonProperty("contactType")]
        public string ContactType { get; set; }

        [JsonProperty("parentId")]
        public int? ParentId { get; set; }

        [JsonProperty("parentTradeNum")]
        public string ParentTradeNum { get; set; }

        [JsonProperty("gunnable")]
        public bool? Gunnable { get; set; }

        [JsonProperty("fee")]
        public decimal? Fee { get; set; }

        [JsonProperty("children")]
        public List<PingCangLilyTrade> Children { get; set; }
    }

    public class PingCangLilyTrades
    {
        [JsonProperty("total")]
        public int Total { get; set; }

        [JsonProperty("rows")]
        public List<PingCangLilyTrade> TradeRows { get; set; }

        [JsonProperty("code")]
        public int Code { get; set; }

        [JsonProperty("msg")]
        public string Msg { get; set; }
    }
    #endregion


    #region lily违约相关实体类
    public class WeiYueChildTrade
    {
        public List<object> Children { get; set; }
        public string ContactPerson { get; set; }
        public string ContactType { get; set; }
        public string CounterParty { get; set; }
        public int CreateBy { get; set; }
        public string CreateTime { get; set; }
        public string DeliveryTime { get; set; }
        public string Direction { get; set; }
        public int JiaogeStatus { get; set; }
        public string MarketMakerName { get; set; }
        public int? ParentId { get; set; }
        public decimal Price { get; set; }
        public int RealTradeId { get; set; }
        public string Remark { get; set; }
        public int Status { get; set; }
        public string Target { get; set; }
        public string TradeNum { get; set; }
        public string TraderName { get; set; }
        public string Tscode { get; set; }
        public string UpdateTime { get; set; }
        public string UserTradeNum { get; set; }
        public string Volume { get; set; }
        public decimal WeiyueAmount { get; set; }
        public string WeiyuePerson { get; set; }
        public int YanjiuyuanId { get; set; }
        public string YanjiuyuanName { get; set; }
    }

    public class WeiYueTradeResponse
    {
        public List<WeiYueChildTrade> Value { get; set; }
        public string Code { get; set; }
        public string Message { get; set; }
    }

    #endregion


    #region lily聊天
    public class LilyChatMessage
    {
        public string Id { get; set; }
        public int ChatId { get; set; }
        public string ChatMessage { get; set; }
        public int BrokerId { get; set; }
        public int Direction { get; set; }
        public DateTime CreateTime { get; set; }
        public int? TradeId { get; set; }
        public bool? IsTrade { get; set; }
        public DateTime UpdateTime { get; set; }
        public string ChannelId { get; set; }
    }
    #endregion
    #endregion




}
